package org.example.backend.demos.web.Util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.apache.logging.log4j.util.Strings;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.UUID;

/**
 * jwt工具生成token防伪作用可以存储用户信息
 */
@Component
public class JwtUtil {

    private static final long tokenExpiration = 5 * 60 * 10000;



    private static final String SECRET_KEY = "my-secure-secret-key-with-sufficient-length-for-hs256-algorithm";
    private static final Key signingKey = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

    public static String createToken(String username) {

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setSubject(username)
                .signWith(signingKey, SignatureAlgorithm.HS256)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .compact();

    }

    public static Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(signingKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    public static boolean isTokenExpired(String token) {
        try {
            Claims claims = parseToken(token);
            return claims.getExpiration().before(new Date());
        } catch (ExpiredJwtException e) {
            // token已过期
            return true;
        } catch (Exception e) {
            // 其他异常情况也认为token无效
            return true;
        }
    }

}